<template>
    <div class="main">
        <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm">
            <el-form-item prop="input">
                <el-input v-model="ruleForm.input" :show-password="isPassword" clearable :placeholder="placeholder"
                    :type="type" autocomplete="off">
                    <template #prepend>新的{{ text }}</template>
                </el-input>
            </el-form-item>
            <el-form-item prop="repeatInput">
                <el-input v-model="ruleForm.repeatInput" :show-password="isPassword" clearable placeholder="请再次输入"
                    :type="type" autocomplete="off">
                    <template #prepend>确认{{ text }}</template>
                </el-input>
            </el-form-item>
        </el-form>
        <el-button type="primary" @click="next">下一步</el-button>
    </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/index.js';
import axios from 'axios';
import type { FormInstance, FormRules } from 'element-plus'
import { storeToRefs } from 'pinia';
let placeholder = computed(() => {
    return '请输入' + text
})
let User = useUserStore()
let { user } = storeToRefs(User)
let { username } = user.value
let isPassword = ref()
let url: string;
let { nextStep, type, text, validate } = defineProps<{
    nextStep: Function,
    type: string,
    text: string,
    validate: any[]
}>()
onMounted(() => {
    isPassword.value = text === 'password'
    url = type === 'password' ? 'password' : 'email'
})
let ruleFormRef = ref<FormInstance>()
let ruleForm = reactive({
    input: '',
    repeatInput: ''
})
const validateRepeatInput = (rule: any, value: any, callback: any) => {
    if (value && value !== ruleForm.input) {
        return callback('两次输入不一致')
    }
    return true
}
const rules = reactive<FormRules>({
    input: validate,
    repeatInput: [{ validator: validateRepeatInput, trigger: 'blur' }],
})
let next = () => {
    ruleFormRef.value?.validate(async (v) => {
        if (v) {
            let { data } = await axios.patch('user/change/' + url, {
                username,
                [url]: ruleForm.input
            })
            if (data.code === '0000') {
                ElMessage.success(data.msg)
                User.setUser(data.data)
                nextStep();
                return
            }
            ElMessage.error(data.msg)
        }
    })
}
</script>


<style scoped lang="less">
.main {
    width: 300px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}
</style>
